//
//  SettingViewController.m
//  MiAiApp
//
//  Created by voidcat on 2017/6/16.
//  Copyright © 2017年 voidcat. All rights reserved.
//

#import "SettingViewController.h"
#import "BaseTableViewCell.h"
#import "HSBaseCellModel.h"
#import "BlackViewController.h"
#import "RootWebViewController.h"
#import "SuggestViewController.h"
#import <WebKit/WebKit.h>
#import "MineLogic.h"
#import "Version.h"
#import "LanguageViewController.h"
@interface SettingViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>

@property (nonatomic,copy) NSArray * dataArray;//数据源
@property (nonatomic,copy) QMUIDialogTextFieldViewController *dialogViewController;
@property(nonatomic, strong) UISwitch *blockSwitch;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"设置");
    [self setupUI];
    [self getData];
}
#pragma mark ————— 初始化页面 —————
-(void)setupUI{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.frame = self.view.bounds;
    [self.tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"BaseTableViewCell"];
    [self.view addSubview:self.tableView];
    
    
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 109)];
    
    UIButton *logoutBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    logoutBtn.frame = CGRectMake(0, 20, footView.width, 49);
    logoutBtn.titleLabel.font = SYSTEMFONT(16);
    [logoutBtn setTitle:ASLocalizedString(@"退出登录")forState:UIControlStateNormal];
    [logoutBtn setTitleColor:KBlackColor forState:UIControlStateNormal];
    logoutBtn.backgroundColor = KWhiteColor;
    [logoutBtn addTarget:self action:@selector(logoutAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:logoutBtn];
    
    self.tableView.tableFooterView = footView;
}

#pragma mark ————— 数据源 —————
-(void)getData{
    HSBaseCellModel *pushCofigModel = [HSBaseCellModel new];
    pushCofigModel.title = ASLocalizedString(@"推送消息设置");
    pushCofigModel.identifier = 9000;
    pushCofigModel.selectionStyle = UITableViewCellSelectionStyleNone;
    pushCofigModel.isShowArrow = YES;

    
    HSBaseCellModel *blackList = [HSBaseCellModel new];
    blackList.title = ASLocalizedString(@"黑名单");
    blackList.identifier = 9003;
    blackList.selectionStyle = UITableViewCellSelectionStyleNone;
    blackList.isShowArrow = YES;
    
    
    
    HSBaseCellModel *soundsCofigModel = [HSBaseCellModel new];
    soundsCofigModel.title = ASLocalizedString(@"声音");
    soundsCofigModel.identifier = 9001;
    soundsCofigModel.selectionStyle = UITableViewCellSelectionStyleNone;
    soundsCofigModel.detailText = ASLocalizedString(@"默认");
    soundsCofigModel.isShowArrow = NO;
    
    HSBaseCellModel *cleanCofigModel = [HSBaseCellModel new];
    cleanCofigModel.title = ASLocalizedString(@"清除缓存");
    cleanCofigModel.identifier = 9002;
    cleanCofigModel.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    HSBaseCellModel *VersionModel = [HSBaseCellModel new];
    VersionModel.title = NSStringFormat(ASLocalizedString(@"当前版本"));
    VersionModel.identifier = 9005;
    VersionModel.selectionStyle = UITableViewCellSelectionStyleNone;
//    VersionModel.detailText = @"v1.0.0";
    
    
    HSBaseCellModel *language = [HSBaseCellModel new];
    language.title = NSStringFormat(ASLocalizedString(@"语言"));
    language.identifier = 9006;
    language.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    CFShow(infoDictionary);
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    
    VersionModel.detailText = app_Version;

    NSUInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
    
    NSString *clearCacheName;
    if (tmpSize >= 1024*1024*1024) {
        clearCacheName = [NSString stringWithFormat:ASLocalizedString(@"清理缓存(%0.2fG)"),tmpSize /(1024.f*1024.f*1024.f)];
    }else if (tmpSize >= 1024*1024) {
        clearCacheName = [NSString stringWithFormat:ASLocalizedString(@"清理缓存(%0.2fM)"),tmpSize /(1024.f*1024.f)];
    }else{
        clearCacheName = [NSString stringWithFormat:ASLocalizedString(@"清理缓存(%0.2fK)"),tmpSize / 1024.f];
    }
    
    
    cleanCofigModel.detailText = clearCacheName;
    cleanCofigModel.isShowArrow = NO;
    
    HSBaseCellModel *aboutCofigModel = [HSBaseCellModel new];
    aboutCofigModel.title = ASLocalizedString(@"关于我们");
    aboutCofigModel.identifier = 9003;
    aboutCofigModel.selectionStyle = UITableViewCellSelectionStyleNone;
    aboutCofigModel.isShowArrow = YES;
    
    HSBaseCellModel *QQModel = [HSBaseCellModel new];
    QQModel.title = ASLocalizedString(@"投诉建议");
    QQModel.identifier = 9007;
    QQModel.selectionStyle = UITableViewCellSelectionStyleNone;
    QQModel.isShowArrow = YES;
    
    HSBaseCellModel *disturb = [HSBaseCellModel new];
    disturb.title = ASLocalizedString(@"勿扰");
    disturb.identifier = 9008;
    disturb.selectionStyle = UITableViewCellSelectionStyleNone;
    disturb.isShowArrow = YES;
    
    NSArray *one = @[];
    NSMutableArray *two = [NSMutableArray arrayWithArray:@[soundsCofigModel,blackList,cleanCofigModel,aboutCofigModel,QQModel,disturb,VersionModel,language]];
    
    

    if(KGlobalVariable.appmodel.open_custom_video_charge_coin == 1)
    {
        if (!(IsCurrentUserMale)) {
            HSBaseCellModel *cleanCofigModel = [HSBaseCellModel new];
            cleanCofigModel.title = ASLocalizedString(@"设置按时付费价格");
            cleanCofigModel.identifier = 9006;
            cleanCofigModel.selectionStyle = UITableViewCellSelectionStyleNone;
            [two insertObject:cleanCofigModel atIndex:two.count-2];
            //        [two addObject:cleanCofigModel];
        }
    }
    
    _dataArray = @[one,two];
    [self.tableView reloadData];
    
}

#pragma mark ————— tableView 代理 —————
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dataArray[section] count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 49.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //如果是最后一个section
    if(section == self.dataArray.count - 1){
        return 0;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    //如果是最后一个section
    if(section == self.dataArray.count - 1){
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    [view setBackgroundColor:CViewBgColor];
    return view;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseTableViewCell" forIndexPath:indexPath];
    HSBaseCellModel *model = _dataArray[indexPath.section][indexPath.row];
    cell.selectionStyle = model.selectionStyle;
    cell.textLabel.text = model.title;
    cell.customDetailText = model.detailText;
    cell.accessoryType = model.isShowArrow ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    if([model.title isEqualToString:ASLocalizedString(@"勿扰")])
    {
        cell.accessoryView = self.blockSwitch; //switch
    }
    else
    {
        cell.accessoryView = nil;
    }

    
    return cell;
}

-(UISwitch *)blockSwitch
{
    if (_blockSwitch == nil) {
        _blockSwitch = [[UISwitch alloc]init];
        _blockSwitch.onTintColor = RGBCOLOR(63, 125, 194);
        [_blockSwitch addTarget:self action:@selector(blockSwitchChanged:) forControlEvents:UIControlEventValueChanged];
    }
    _blockSwitch.on = curUser.is_open_do_not_disturb;
    return _blockSwitch;
}
    
-(void)blockSwitchChanged:(id)sender
{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    
    //不回调说明请求错误
    [MineLogic requestSetDoNotDisturtWithBock:^(id selfPtr) {
        
    }];
    
    if (isButtonOn) {
        NSLog(ASLocalizedString(@"开"));
    }else {
        NSLog(ASLocalizedString(@"关"));
    }
}
    
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HSBaseCellModel *model = _dataArray[indexPath.section][indexPath.row];
    NSLog(ASLocalizedString(@"点击了 %@"),model.title);
    if([model.title isEqualToString:ASLocalizedString(@"清除缓存")])
    {
        [self clearCache];
    }
    else if([model.title isEqualToString:ASLocalizedString(@"黑名单")])
    {
        [self gotoBlackList];
    }
    else if([model.title isEqualToString:ASLocalizedString(@"关于我们")])
    {
        [self gotoAboutMe];
    }
    else if([model.title isEqualToString:ASLocalizedString(@"设置按时付费价格")])
    {
        [self alertSetVideoCoin];
    }
    else if([model.title isEqualToString:ASLocalizedString(@"投诉建议")])
    {
        [self goToSuggest];
    }
    else if([model.title isEqualToString:ASLocalizedString(@"语言")])
    {
        [self gotoLanguage];
    }
//    switch (indexPath.row) {
//        case 9000:
//        {
//            NSLog(ASLocalizedString(@"点击了 %@"),model.title);
//        }
//            break;
//            
//        default:
//            break;
//    }
}

- (void)goToSuggest {
    SuggestViewController *vc = [[SuggestViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)gotoLanguage {
    LanguageViewController *vc = [[LanguageViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)alertSetVideoCoin {
    _dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
    _dialogViewController.title = ASLocalizedString(@"修改收费金额");
    
    _dialogViewController.textField.placeholder = ASLocalizedString(@"0代表系统默认金额");
    _dialogViewController.textField.keyboardType = UIKeyboardTypeNumberPad;
    [_dialogViewController addCancelButtonWithText:ASLocalizedString(@"取消")block:^(QMUIDialogViewController *dialogViewController) {

    }];
    
    __weak __typeof(self)weakSelf = self;
    _dialogViewController.buttonBackgroundColor = [UIColor whiteColor];
    [_dialogViewController addSubmitButtonWithText:ASLocalizedString(@"修改")block:^(QMUIDialogViewController *dialogViewController) {
        
        //http://192.168.0.109/mapi/public/index.php/api/user_api/change_video_line_money?uid=100114&token=ecf209ab0e2690de911bbcddbd023bb2&coin=22
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"change_video_line_money"];
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:weakSelf.dialogViewController.textField.text forKey:@"coin"];
        
        [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {

        } success:^(id responseObject) {
            [MBProgressHUD showTopTipMessage:ASLocalizedString(@"修改成功")];
            
            [weakSelf.dialogViewController hide];
        } failure:^(NSString *error) {
            [MBProgressHUD showTopTipMessage:error];
        } hasCache:NO];
        
    }];
    [_dialogViewController show];
}

- (void)gotoBlackList {
    BlackViewController *black = [[BlackViewController alloc] init];
    [self.navigationController pushViewController:black animated:NO];
}

-(void)clearCache
{
    [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"正在清除图片缓存")];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [[HUDHelper sharedInstance] syncStopLoadingMessage:ASLocalizedString(@"图片缓存清除完毕")];
         [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"正在清除网页缓存")];
        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            [MBProgressHUD showTopTipMessage:ASLocalizedString(@"缓存清理完毕")];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self getData];
            });
        }];

    }];
}

- (void)gotoAboutMe {
    RootWebViewController *web = [[RootWebViewController alloc] initWithUrl:KGlobalVariable.appmodel.app_h5.about_me];
    web.title = ASLocalizedString(@"关于我们");
    [self.navigationController pushViewController:web animated:YES];
}

- (void)gotoQQ {
    // 判断手机是否安装QQ
//    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
//
//
//    }else{
        //用来接收临时消息的客服QQ号码(注意此QQ号需开通QQ推广功能,否则陌生人向他发送消息会失败)
        NSString *QQ = KGlobalVariable.appmodel.custom_service_qq;
        //调用QQ客户端,发起QQ临时会话
        NSString *url = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",QQ];
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
        if(!success)
        {
            [HUDHelper alert:[NSString stringWithFormat:@"QQ:%@",KGlobalVariable.appmodel.custom_service_qq]];

        }
    }];
    
//    }

}
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark ————— 退出登录 —————
-(void)logoutAction:(UIButton *)btn{
    [self AlertWithTitle:nil message:ASLocalizedString(@"确定要退出吗？")andOthers:@[ASLocalizedString(@"取消"),ASLocalizedString(@"确定")] animated:YES action:^(NSInteger index) {
        NSLog(@"%ld",index);
        if (index == 1) {
            [userManager logout:nil];
        }
    }];
}
#pragma mark ————— 计算缓存大小 —————
// 显示缓存大小
-(float)filePath{
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    return [ self folderSizeAtPath :cachPath];
}

-(long long)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }
    return 0;
}
-(float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    cachePath=[cachePath stringByAppendingPathComponent:path];
    long long folderSize=0;
    if ([fileManager fileExistsAtPath:cachePath])
    {
        NSArray *childerFiles=[fileManager subpathsAtPath:cachePath];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];
            long long size=[self fileSizeAtPath:fileAbsolutePath];
            folderSize += size;
            NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
            
        }
        return folderSize/1024.0/1024.0;
    }
    return 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
